var stats;

//初始化
function init() {
    stats = new Stats();
    var sds = stats.domElement.style;
    sds.position = 'absolute';
    sds.right = '0px';
    sds.top = '0px';
    document.body.appendChild(stats.domElement);

    var t = document.createElement('table');
    var index = 0;
    
    for(var i = 0; i < 64; i += 1) {
        var tr = t.insertRow(-1);
        for(var j = 0; j < 64; j += 1) {
            var td = tr.insertCell(-1);
            td.style.backgroundColor = '#000';
            var cell = { //属性变量
                td: td,
                value: 0
            };
            var tween = new TWEEN.Tween(cell)
                        .to({
                            value: 1
                        }, 8000)
                        .delay((0.001 * index + Math.random()) * 500)
                        .easing(TWEEN.Easing.Elastic.InOut)
                        .onUpdate(function(obj) {
                            var c = obj.value * 0xff;
                            obj.td.style.setProperty('background-color', `rgb(${c}, 0, 0)`);
                        });
            
            var tweenBack = new TWEEN.Tween(cell)
                            .to({
                                value: 0
                            }, 4000)
                            .delay((0.001 * index + Math.random()) * 500)
                            .easing(TWEEN.Easing.Elastic.InOut)
                            .onUpdate(function(obj) {
                                var c = obj.value * 0xff;
                                obj.td.style.setProperty('background-color', `rgb(${c}, 0, 0)`);
                            });

            tween.chain(tweenBack);
            tweenBack.chain(tween);

            tween.start();
            index++;
        }
    }

    document.getElementById('target').appendChild(t);
}

//动画函数
function animate(time) {
    requestAnimationFrame(animate);

    TWEEN.update(time);
    stats.update();
}

init();
animate();